package com.rpp.utils;

import com.rpp.servlet.HttpServlet;
import com.rpp.servlet.RequestMapping;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author rpp
 * @Date 2020/7/22 11:27 下午
 */
public class ResourceUtil {

    public static List<RequestMapping> loadServlet(File webXmlFile, String path) {

        List<RequestMapping> list = new ArrayList();
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new FileInputStream(webXmlFile));
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>rpp</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>com.rpp.servlet.MyServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /rpp
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                MyClassLoader myClassLoader = new MyClassLoader(path + "/");
                HttpServlet servlet = (HttpServlet) myClassLoader.findClass(servletClass).newInstance();
                list.add(new RequestMapping(urlPattern, servlet));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
